package cn.juque.redoctopus.disruptor.event;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.juque.common.base.DisruptorBody;
import cn.juque.common.disruptor.IBusinessEventService;
import cn.juque.luceneplus.service.DocumentPlusService;
import cn.juque.redoctopus.api.constants.LogIndexEnum;
import cn.juque.redoctopus.bo.disruptor.LogBO;
import java.io.IOException;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * @author nuoka
 * @version 1.0.0
 * <li>IntelliJ IDEA</li>
 * <li></li>
 * @date 2021/8/25 10:34
 **/
@Service("logEventService")
public class LogEventServiceImpl implements IBusinessEventService {

    public static final String BEAN_NAME="logEventService";

    @Resource
    private DocumentPlusService documentPlusService;

    /**
     * 具体消费者的实现
     *
     * @param disruptorBodyBO 消息体
     */
    @Override
    public void invoke(DisruptorBody disruptorBodyBO) throws IOException {
        if(disruptorBodyBO instanceof LogBO) {
            LogBO logBO = (LogBO) disruptorBodyBO;
            Map<String, Object> map = toMap(logBO);
            this.documentPlusService.addDocument(LogIndexEnum.INDEX_NAME.getCode(), map);
        }
    }

    /**
     * 转换成map
     * @param logBO LogBO
     * @return Map<String, Object>
     */
    private Map<String, Object> toMap(LogBO logBO) {
        Map<String, Object> map = MapUtil.newHashMap();
        map.put(LogIndexEnum.SERVICE_NO.getCode(), logBO.getServiceNo());
        map.put(LogIndexEnum.SERVICE_NAME.getCode(), logBO.getServiceName());
        map.put(LogIndexEnum.LEVEL.getCode(), logBO.getLevel());
        long logTime = null == logBO.getTimestamp() ? System.currentTimeMillis() : logBO.getTimestamp();
        map.put(LogIndexEnum.LOG_TIME.getCode(), logTime);
        if(CharSequenceUtil.isNotEmpty(logBO.getMessage())) {
            map.put(LogIndexEnum.MESSAGE.getCode(), logBO.getMessage());
        }
        if(CharSequenceUtil.isNotEmpty(logBO.getThrowable())) {
            map.put(LogIndexEnum.THROWABLE.getCode(), logBO.getThrowable());
        }
        map.put(LogIndexEnum.IP.getCode(), logBO.getIp());

        return map;
    }
}
